package moon.voice.service.VoiceOperaHandler.handler;

import lombok.extern.slf4j.Slf4j;
import moon.voice.entity.AudioChunk;
import moon.voice.entity.VoiceProcessResult;
import moon.voice.service.VoiceStreamService;
import org.apache.dubbo.common.stream.StreamObserver;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;

/**
 *
 */
@Service
@Slf4j
public class VoiceHandlerService implements VoiceStreamService {

    @Override
    public StreamObserver<AudioChunk> processAudioStream(StreamObserver<VoiceProcessResult> responseObserver) {
       return new StreamObserver<AudioChunk>() {
            private final ByteArrayOutputStream audioBuffer = new ByteArrayOutputStream();
            private String currentFormat;

            @Override
            public void onNext(AudioChunk chunk) {
                // 接收音频分片
                if (currentFormat == null) {
                    currentFormat = chunk.getFormat();
                }

                try {
                    audioBuffer.write(chunk.getData());

                    // 示例：实时转码（伪代码）
//                    byte[] processedChunk = F.transcode(chunk.getData(), currentFormat, "WAV");

                    // 实时返回处理结果
                    VoiceProcessResult result = new VoiceProcessResult();
                    result.setMessage("Processed chunk: " + chunk.getData().length + " bytes");
//                    result.setAudioData(processedChunk); // 返回处理后的分片
                    responseObserver.onNext(result);
                } catch (Exception e) {
                    responseObserver.onError(e);
                }
            }

            @Override
            public void onError(Throwable t) {
                log.error("Stream error", t);
            }

            @Override
            public void onCompleted() {
                // 整体处理完成
                VoiceProcessResult finalResult = new VoiceProcessResult();
                finalResult.setMessage("COMPLETED");
                responseObserver.onNext(finalResult);
                responseObserver.onCompleted();
            }
        };
    }


}
